﻿using System;
using System.Data;
using System.Collections;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AnyOffice.Components;
using AnyOffice.DAL;
using AnyOffice.BIZ;
using AnyOffice.Model;
using System.Reflection;
using System.IO;
using log4net;
using Webdiver;

namespace AnyOffice.general.email
{
    public partial class new1 : ModulePage
    {

        private static ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

      
        protected void btnAddFile_Click(object sender, EventArgs e)
        {
            if (this.fileAttach.PostedFile.ContentLength > 0)
            {
                try
                {
                    string uniqueTempPath = this.ViewState["UniqueTempPath"].ToString();
                    if (uniqueTempPath == "")
                    {
                        uniqueTempPath = AttachmentBiz.GetUniqueTempPath();
                        this.ViewState["UniqueTempPath"] = uniqueTempPath;
                    }
                    Upload upload = new Upload();
                    upload.AutoCreateDirectory = true;
                    upload.OverwriteFile = true;
                    upload.DestinationPath = uniqueTempPath;
                    ConfigManager manager = new ConfigManager();
                    upload.MaxSize = manager.AttachMaxSize;
                    upload.GetFile(this.fileAttach.PostedFile);
                    upload.DoUpload();
                    this.ViewState["TotalSize"] = Convert.ToInt32(this.ViewState["TotalSize"]) + upload.FileSize;
                    ArrayList list = (ArrayList)this.ViewState["FileList"];
                    list.Add(Path.GetFileName(this.fileAttach.PostedFile.FileName));
                    this.ViewState["FileList"] = list;
                    this.ViewState["FileNums"] = Convert.ToInt32(this.ViewState["FileNums"].ToString()) + 1;
                    this.ltbFileList.Items.Add(Path.GetFileName(this.fileAttach.PostedFile.FileName));
                    if (Convert.ToInt32(this.ViewState["FileNums"].ToString()) != 0)
                    {
                        this.ltbFileList.Rows = Convert.ToInt32(this.ViewState["FileNums"].ToString());
                    }
                    if (Convert.ToInt32(this.ViewState["FileNums"].ToString()) > 0)
                    {
                        this.pnlAttach.Visible = true;
                    }
                }
                catch (Exception exception)
                {
                    if (log.IsErrorEnabled)
                    {
                        log.Error("", exception);
                    }
                }
            }
        }
        protected void btnRemoveFile_Click(object sender, EventArgs e)
        {
            if (this.ltbFileList.Items.Count != 0)
            {
                try
                {
                    ArrayList list = (ArrayList)this.ViewState["FileList"];
                    list.Remove(this.ltbFileList.SelectedItem.Text);
                    this.ViewState["FileList"] = list;
                    string fileName = this.ViewState["UniqueTempPath"].ToString() + this.ltbFileList.SelectedItem.Text;
                    FileInfo info = new FileInfo(fileName);
                    if (info.Exists)
                    {
                        this.ViewState["TotalSize"] = Convert.ToInt32(this.ViewState["TotalSize"]) - info.Length;
                        if (File.Exists(fileName))
                        {
                            File.Delete(fileName);
                        }
                    }
                    this.ViewState["FileNums"] = Convert.ToInt32(this.ViewState["FileNums"].ToString()) - 1;
                    if (Convert.ToInt32(this.ViewState["FileNums"].ToString()) >= 1)
                    {
                        this.ltbFileList.Rows = Convert.ToInt32(this.ViewState["FileNums"].ToString());
                    }
                    this.ltbFileList.Items.Remove(this.ltbFileList.SelectedItem.Text);
                    if (Convert.ToInt32(this.ViewState["FileNums"].ToString()) == 0)
                    {
                        if (Directory.Exists(this.ViewState["UniqueTempPath"].ToString()))
                        {
                            Directory.Delete(this.ViewState["UniqueTempPath"].ToString());
                        }
                        this.ViewState["UniqueTempPath"] = "";
                        this.pnlAttach.Visible = false;
                    }
                }
                catch (Exception exception)
                {
                    if (log.IsErrorEnabled)
                    {
                        log.Error("", exception);
                    }
                }
            }
        }
        protected void btnSend_Click(object sender, EventArgs e)
        {
            string attachmentId = "";
            try
            {
                if (this.ViewState["UniqueTempPath"].ToString() != "")
                {
                    string uniquePath = AttachmentBiz.GetUniquePath(out attachmentId);
                    Directory.Move(this.ViewState["UniqueTempPath"].ToString(), uniquePath);
                    AttachmentData data = new AttachmentData();
                    AttachmentDao dao = new AttachmentDao();
                    ArrayList list = (ArrayList)this.ViewState["FileList"];
                    for (int j = 0; j < list.Count; j++)
                    {
                        FileInfo info = new FileInfo(uniquePath + list[j].ToString());
                        if (info.Exists)
                        {
                            data.Type = 1;
                            data.AttachmentId = attachmentId;
                            data.Name = info.Name;
                            data.AddTime = DateTime.Now;
                            data.TotalSize = (int)info.Length;
                            data.UserId = base.User.Identity.Name;
                            dao.Insert(base.Conn, data);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (log.IsErrorEnabled)
                {
                    log.Error("", exception);
                }
            }
            EmailData data2 = new EmailData();
            EmailDao dao2 = new EmailDao();
            if (attachmentId != string.Empty)
            {
                data2.AttachmentId = attachmentId;
            }
            data2.ToId2 = this.ToId.Value;
            data2.CopyToId = this.CopyToId.Value;
            data2.SecretToId = this.SecretToId.Value;
            data2.FromId = base.User.Identity.Name;
            data2.Subject = this.txtSubject.Text;
            data2.TotalSize = (Convert.ToInt32(this.ViewState["TotalSize"].ToString()) + this.txtSubject.Text.Length) + this.txtContent.Value.Length;
            data2.Content = this.txtContent.Value;
            data2.Important = Convert.ToInt32(this.rblImportant.SelectedValue);
            string str3 = this.ToId.Value;
            if (this.CopyToId.Value != string.Empty)
            {
                str3 = str3 + this.CopyToId.Value;
            }
            if (this.SecretToId.Value != string.Empty)
            {
                str3 = str3 + this.SecretToId.Value;
            }
            if (str3.EndsWith(","))
            {
                str3 = str3.Substring(0, str3.Length - 1);
            }
            string[] strArray = str3.Split(new char[] { ',' });
            for (int i = 0; i < strArray.Length; i++)
            {
                data2.ToId = strArray[i];
                dao2.Insert(base.Conn, data2);
            }
            if (this.ckbSms.Checked || this.ckbMobile.Checked)
            {
                SmsData data3 = new SmsData();
                SmsDao dao3 = new SmsDao();
                data3.Type = 2;
                data3.FromId = base.User.Identity.Name;
                data3.ToIdList = str3;
                data3.Content = "请查收我的邮件！\n主题：" + this.txtSubject.Text;
                data3.RemindFlag = true;
                data3.SendTime = DateTime.Now;
                dao3.BizSend(base.Conn, data3, this.ckbSms.Checked, this.ckbMobile.Checked);
            }
            this.pnlMain.Visible = false;
            this.lblMessage.Text = base.ShowPrompt("邮件已发送", "new.aspx");
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                UserCache cache = new UserCache();
                if ((cache.EmailCapacity != 0) && (new EmailBoxDao().InboxSize(base.Conn, base.User.Identity.Name) > ((cache.EmailCapacity * 1024) * 1024)))
                {
                    this.pnlMain.Visible = false;
                    this.lblMessage.Text = base.ShowWarning("您的邮箱已超过容量限制，请清除您的无用邮件！", "index.aspx");
                }
                else
                {
                    string str = (Request.QueryString["action"] != null) ? Request.QueryString["action"].ToString() : "";
                    int emailId = (Request.QueryString["email_id"] != null) ? int.Parse(Request.QueryString["email_id"].ToString()) : 0;
                    this.ViewState["page"] = (Request.QueryString["page"] == null) ? "1" : Request.QueryString["page"].ToString();
                    if ((str == string.Empty) || (emailId == 0))
                    {
                        this.pnlMain.Visible = false;
                        this.lblMessage.Text = base.ShowPrompt("无此邮件");
                    }
                    else
                    {
                        DataTable table = new EmailDao().SelectByEmailId(base.Conn, emailId, base.User.Identity.Name);
                        if (table.Rows.Count == 0)
                        {
                            this.pnlMain.Visible = false;
                            this.lblMessage.Text = base.ShowPrompt("无此邮件");
                        }
                        else
                        {
                            if (str == "reply")
                            {
                                this.ToId.Value = table.Rows[0]["ToId2"].ToString();
                                this.ToName.Text = StringHelper.GeReplyNames(base.Conn, table.Rows[0]["ToId2"].ToString());
                                this.txtSubject.Text = "回复:" + table.Rows[0]["Subject"].ToString();
                                this.txtContent.Value = (table.Rows[0]["UserName"] != DBNull.Value) ? (table.Rows[0]["UserName"].ToString() + "，您好！") : "";
                              //  this.txtContent.Value = this.txtContent.Value + "========您在" + table.Rows[0]["SendTime"].ToString() + "的来信中写道：========<div>";
                            //    this.txtContent.Value = this.txtContent.Value + ((table.Rows[0]["Content"] != DBNull.Value) ? table.Rows[0]["Content"].ToString() : "");
                              //  this.txtContent.Value = this.txtContent.Value + "===============================================<div>";
                              // this.txtContent.Value = this.txtContent.Value + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;致<div>";
                             //   this.txtContent.Value = this.txtContent.Value + "礼！";
                                //this.txtContent.Value = Server.HtmlDecode(this.txtContent.Value);
                               
                            }
                            else
                            {
                                this.txtSubject.Text = "转发:" + table.Rows[0]["Subject"].ToString();
                                this.txtContent.Value = (table.Rows[0]["Content"] != DBNull.Value) ? table.Rows[0]["Content"].ToString() : "";
                            }
                            string attachmentId = (table.Rows[0]["AttachmentId"] != DBNull.Value) ? table.Rows[0]["AttachmentId"].ToString() : "";
                            this.ViewState["OldAttachmentId"] = attachmentId;
                            this.ViewState["FileNums"] = 0;
                            this.ViewState["FileList"] = new ArrayList();
                            this.ViewState["UniqueTempPath"] = "";
                            this.ViewState["TotalSize"] = 0;
                            this.btnAddFile.Attributes.Add("onclick", "return CheckFile();");
                            if ((attachmentId != string.Empty) && (str == "forward"))
                            {
                                DataTable table2 = new AttachmentDao().SelectByAttachmentId(base.Conn, attachmentId);
                                if (table2.Rows.Count > 0)
                                {
                                    try
                                    {
                                        this.ViewState["FileNums"] = table2.Rows.Count;
                                        ArrayList list = new ArrayList();
                                        string savedPath = AttachmentBiz.GetSavedPath(attachmentId);
                                        string uniqueTempPath = AttachmentBiz.GetUniqueTempPath();
                                        this.ViewState["UniqueTempPath"] = uniqueTempPath;
                                        AttachmentBiz.Copy(savedPath, uniqueTempPath);
                                        int num3 = 0;
                                        for (int i = 0; i < table2.Rows.Count; i++)
                                        {
                                            list.Add(table2.Rows[i]["Name"].ToString());
                                            num3 += Convert.ToInt32(table2.Rows[i]["TotalSize"].ToString());
                                        }
                                        this.ltbFileList.DataSource = list;
                                        this.ltbFileList.DataBind();
                                        this.ltbFileList.Rows = table2.Rows.Count;
                                        this.ViewState["FileList"] = list;
                                        this.ViewState["TotalSize"] = num3;
                                        this.pnlAttach.Visible = true;
                                    }
                                    catch (Exception exception)
                                    {
                                        if (log.IsErrorEnabled)
                                        {
                                            log.Error("提交前 - 附件上传相关", exception);
                                        }
                                    }
                                }
                            }
                            this.btnSend.Attributes.Add("onclick", "return CheckForm();");
                            this.ckbMobile.Visible = SmsDao.IsMobile(SmsDao.SmsType.Email);
                        }
                    }
                }
            }
        }
 
    }
}
